<template>
  <div>
    <!-- 显示已选择的文件 -->
    <div
      v-loading="loading"
      class="img-upload-box"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.6)"
    >
      <div v-for="(file,index) in fileList" :key="index" class="avatar-uploader" :class="[isVideo(file) ? 'video-container' : '', multiple ? 'multiple' : '']">
        <!-- 视频预览 -->
        <video
            v-if="isVideo(file)"
            style="width: 100%; height: 100%"
            controls
            :src="file"
        >
          您的浏览器不支持视频播放
        </video>
        <!-- 图片预览 -->
        <el-image
            v-else
            style="width: 100%; height: 100%"
            :preview-src-list="fileList"
            :src="file"
            fit="contain"
        >
          <template #error>
            <img src="@/assets/file.png" alt="" fit="contain" style="width: 100%">
          </template>
        </el-image>
        <i class="el-icon-error close-icon" @click="onClose(index)" />
      </div>

      <!-- 点击打开文件选择器对话框 -->
      <div v-if="multiple || !fileList.length" :class="['avatar-uploader active', multiple ? 'multiple' : '']" @click="openFileDialog">
        <i class="el-icon-plus avatar-uploader-icon" />
      </div>
      <slot />
    </div>

    <!-- 文件选择器对话框 -->
    <el-dialog
      title="选择文件"
      :visible.sync="dialogVisible"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <!-- 引入文件管理页面组件，传入选择模式参数 -->
      <FileManager
        ref="fileManager"
        :selectable="true"
        :multiple="multiple"
        :selected-files="selectedFiles"
        @file-selected="onFileSelected"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog
      title="上传文件"
      :visible.sync="uploadDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-upload
        v-if="uploadDialogVisible"
        class="upload-container"
        drag
        action=""
        :http-request="handleFileUpload"
        :limit="1"
        :show-file-list="true"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadFile, http } from '@/api'
import dayjs from 'dayjs'
import FileManager from '@/views/file/index.vue'

export default {
  name: 'FileUpload',
  components: {
    FileManager
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    fileType: {
      type: String,
      default: '' // 可以是 'image', 'video', 'audio' 或空字符串（表示所有类型）
    }
  },
  data() {
    return {
      loading: false,
      fileList: [],
      dialogVisible: false,
      uploadDialogVisible: false,
      selectedFiles: [],
      tempSelectedFiles: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.fileList = (val || '').split(',').filter(el => el)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 打开文件选择器对话框
    openFileDialog() {
      this.dialogVisible = true
      this.tempSelectedFiles = [...this.fileList] // 保存当前选择，以便取消时恢复
      // this.loadFiles()
    },

    // 当文件管理器选择文件时的回调
    onFileSelected(files) {
      this.selectedFiles = files
    },

    // 显示上传对话框
    showUploadDialog() {
      this.uploadDialogVisible = true
    },

    // 处理文件上传
    async handleFileUpload({ file }) {
      try {
        const response = await uploadFile(file)
        if (response && response.data) {
          this.$message.success('文件上传成功')
          this.uploadDialogVisible = false
          // this.loadFiles() // 重新加载文件列表
        }
      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('文件上传失败: ' + (error.message || '未知错误'))
      }
    },



    // 确认选择
    confirmSelection() {
      const selectedFiles = this.$refs.fileManager.getSelectedFiles()
      const urls = selectedFiles.map(file => file.file_url)

      if (this.multiple) {
        this.fileList = urls
      } else if (urls.length > 0) {
        this.fileList = [urls[0]]
      } else {
        this.fileList = []
      }

      this.$emit('change', this.fileList.join(','))
      this.dialogVisible = false
    },

    // 关闭对话框
    handleDialogClose() {
      // 恢复之前的选择
      this.fileList = [...this.tempSelectedFiles]
      this.dialogVisible = false
    },

    // 移除文件
    onClose(index) {
      this.fileList.splice(index, 1)
      this.$emit('change', this.fileList.join(','))
    },

    // 文件类型判断
    isImage(file) {
      return file.endsWith('.png') || file.endsWith('.jpg') || file.endsWith('.jpeg')
    },

    isVideo(file) {
      return file.endsWith('.mp4')
    },

    isImageFile(type) {
      return type && (type.startsWith('image/') || type === 'image')
    },

    isAudioFile(type) {
      return type && (type.startsWith('audio/') || type === 'audio')
    },

    isVideoFile(type) {
      return type && (type.startsWith('video/') || type === 'video')
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 截断文件名
    truncateFilename(filename) {
      if (!filename) return ''
      if (filename.length <= 15) return filename
      const ext = filename.lastIndexOf('.') > 0 ? filename.substring(filename.lastIndexOf('.')) : ''
      const name = filename.substring(0, filename.length - ext.length)
      return name.substring(0, 10) + '...' + (ext ? ext : '')
    }
  }
}
</script>

<style lang="scss">
.file-upload-wrapper {
  display: flex;
  flex-wrap: wrap;
}
.img-upload-box {
  display: flex;
  flex-wrap: wrap;
  .el-upload-list {
    display: none;
  }
  .avatar-uploader {
    width: 240px;
    height: 120px;
    margin-right: 8px;
    margin-bottom: 8px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;

    // 视频预览容器样式
    &.video-container {
      width: 240px;
      height: 120px;
    }
    &.multiple {
      width: 120px;
      height: 120px;
      .avatar-uploader-icon {
        font-size: 24px;
        width: 120px;
        height: 120px;
        line-height: 120px !important;
      }
      .avatar {
        width: 120px;
        height: 120px;
      }
    }
    .close-icon {
      position: absolute;
      right: -8px;
      top: -8px;
      font-size: 24px;
      color: #0bc162;
      cursor: pointer;
    }
    &.active {
      cursor: pointer;
      .close-icon {
        display: none;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 240px;
    height: 120px;
    line-height: 120px !important;
    text-align: center;
  }
  .avatar {
    width: 240px;
    height: 120px;
    display: block;
  }
}
</style>


